package com.amado.easyui2.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.amado.easyui2.dao.DepartmentDao;
import com.amado.easyui2.dao.UserDao;
import com.amado.easyui2.domain.Department;
import com.amado.easyui2.exception.ApiException;
import com.amado.easyui2.enums.ApiErrorEnum;
import com.amado.easyui2.service.DepartmentService;
import com.amado.easyui2.vo.Page;

@Service
public class DepartmentServiceImpl implements DepartmentService {
	@Autowired
	private DepartmentDao departmentDao;
	@Autowired
	private UserDao userDao;

	@Override
	public boolean add(Department department) {
		if(department==null) {
			throw new ApiException(ApiErrorEnum.ERROR_100);
		}
		Department returnDept=departmentDao.getByDeptName(department.getDepartmentName());
		if(returnDept!=null) {
			throw new ApiException(ApiErrorEnum.ERROR_1001);
		}
		departmentDao.add(department);
		return true;
	}
	
	@Override
	public Department getByDeptNumber(String deptNumber) {
		return departmentDao.getByDeptNumber(deptNumber);
	}

	@Override
	public List<Department> list() {
		return departmentDao.listAll();
	}

	@Override
	public boolean delete(Long id) {
		// 查询部门下是否有用户
		// select count(1) from user where dept_num=‘de’and delte_flag=’N’
		// 根据ID得到部门对象
		Department dept = departmentDao.getById(id);
		if (dept == null) {
			throw new ApiException("003","部门不存在，删除失败");
		}
		// 根据部门对象查询有多少用户
		Integer userCount = userDao.selectCountByDeptNumber(dept.getDepartmentNum());
		if (userCount == null) {
			throw new ApiException("004","系统异常");
		}
		if(userCount > 0) {
			throw new ApiException("005","部门下已经有员工，删除失败");
		}
		// 删除部门
		departmentDao.delete(id);
		return true;
	}

	@Override
	public boolean update(Department department) {
		if (department != null) {
			departmentDao.update(department);
			return true;
		}
		return false;
	}

	@Override
	public Page<Department> listAll(Page page) {
		int total = departmentDao.listAllCount();
		Page<Department> newPage = new Page<>();
		newPage.setTotal(total);
		newPage.setRows(departmentDao.listAll(page));
		return newPage;
	}

	@Override
	public List<Department> listAll() {
		return departmentDao.listAll();
	}

}
